﻿#region Licence
// <copyright file="Helpers/HslColor.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
using System.Windows.Media;

#endregion

namespace Helpers.HSL
{
    /// <summary>
    /// Gestion des composantes d'une couleur
    /// </summary>
    public class HslColor : INotifyPropertyChanged
    {

        #region fields

        private const double Scale = 240;

        #endregion

        #region properties

        /// <summary>
        /// Composante dégré de la couleur
        /// </summary>
        private int _hue;
        public int Hue
        {
            get { return _hue; }
            set
            {
                _hue = value;
                OnPropertyChanged(() => Hue);
            }
        }

        /// <summary>
        /// Composante de saturation de la couleur
        /// </summary>
        private int _saturation;
        public int Saturation
        {
            get { return _saturation; }
            set
            {
                _saturation = value;
                OnPropertyChanged(() => Saturation);
            }
        }

        /// <summary>
        /// Composante de luminosité de la couleur
        /// </summary>
        private int _luminosity;
        public int Luminosity
        {
            get { return _luminosity; }
            set
            {
                _luminosity = value;
                OnPropertyChanged(() => Luminosity);
            }
        }

        #endregion

        public HslColor()
        {}

        public HslColor(int hue, int saturation, int luminosity)
        {
            Hue = hue;
            Saturation = saturation;
            Luminosity = luminosity;
        }

        public HslColor(Color color)
        {
            Hue = GetHue(color);
            Saturation = GetSaturation(color);
            Luminosity = GetLuminosity(color);
        }

        #region public

        /// <summary>
        /// permet de générer une couleur à partir d'une teinte, d'une saturation et d'une luminance
        /// </summary>
        /// <returns>Couleur format RGB</returns>
        public Color ToColorRgb()
        {
            if (Hue < 0)
            {
                Hue = 0;
            }

            if (Saturation < 0)
            {
                Saturation = 0;
            }

            if (Luminosity < 0)
            {
                Luminosity = 0;
            }

            const double vMax = 255;
            double to = (double)Hue / (double)60;

            double max = (double)vMax * ((double)Luminosity / (double)Scale);
            double delta = max * ((double)Saturation / (double)Scale);
            double min = max - delta;

            var ent = (int)Math.Truncate(to);

            double b = 0;
            double g = 0;
            double r = 0;

            switch (ent)
            {
                case 0:
                    b = min;
                    g = min + (to * delta);
                    r = max;
                    break;

                case 1:
                    b = min;
                    r = min + ((2 - to) * delta);
                    g = max;
                    break;

                case 2:
                    r = min;
                    b = min + ((to - 2) * delta);
                    g = max;
                    break;

                case 3:
                    r = min;
                    g = min + ((4 - to) * delta);
                    b = max;
                    break;

                case 4:
                    g = min;
                    r = min + ((to - 4) * delta);
                    b = max;
                    break;

                case 5:
                    g = min;
                    b = min + ((6 - to) * delta);
                    r = max;
                    break;
            }

            return new Color() { A = 255, B = Convert.ToByte(b), G = Convert.ToByte(g), R = Convert.ToByte(r) };
        }

        #endregion

        #region  private

        /// <summary>
        /// Obtient la valeur de teinte de la couleur
        /// </summary>
        /// <param name="color">Couleur voulue</param>
        /// <returns>Valeur de la teinte</returns>
        private static int GetHue(Color color)
        {
            double r = color.R;
            double g = color.G;
            double b = color.B;

            double max = Math.Max(r, Math.Max(g, b));
            double min = Math.Min(r, Math.Min(g, b));
            double delta = max - min;

            double to = 0;
            if (delta > 0)
            {
                if (r > g && r > b)
                {
                    to = ((g - b) / delta) % 6;
                }
                else
                {
                    if (g > b && g > r)
                    {
                        to = ((b - r) / delta) + 2;
                    }
                    else
                    {
                        if (b > r && b > g)
                        {
                            to = ((r - g) / delta) + 4;
                        }
                    }
                }
            }
            return Convert.ToInt32(Math.Round(60 * to));
        }

        /// <summary>
        /// Obtient la valeur de saturation de la couleur
        /// </summary>
        /// <param name="color">Couleur voulue</param>
        /// <returns>Valeur de la saturation</returns>
        private static int GetSaturation(Color color)
        {

            double r = color.R;
            double g = color.G;
            double b = color.B;

            if (r == g && r == b)
            {
                return 0;
            }

            double max = Math.Max(r, Math.Max(g, b));
            double min = Math.Min(r, Math.Min(g, b));
            double delta = max - min;

            return Convert.ToInt32(Math.Round(Scale * (delta / max)));
        }

        /// <summary>
        /// Obtient la valeur de luminance de la couleur
        /// </summary>
        /// <param name="color">Couleur voulue</param>
        /// <returns>Valeur de la luminance</returns>
        private static int GetLuminosity(Color color)
        {
            double r = color.R;
            double g = color.G;
            double b = color.B;

            if (r == 0 && g == 0 && b == 0)
            {
                return 0;
            }

            double max = Math.Max(r, Math.Max(g, b));
            double min = Math.Min(r, Math.Min(g, b));

            return Convert.ToInt32(Math.Round((Scale / 255) * max));
        }

        #endregion

        #region NotifyPropertyChanged

        //Inspiré de MVVMLight de Laurent Bugnion
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged<T>(Expression<Func<T>> propertyExpression)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                var propertyName = GetPropertyName<T>(propertyExpression);
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
        {
            if (propertyExpression == null)
            {
                throw new ArgumentNullException("propertyExpression");
            }

            var body = propertyExpression.Body as MemberExpression;

            if (body == null)
            {
                throw new ArgumentException("Invalid argument", "propertyExpression");
            }

            var property = body.Member as PropertyInfo;

            if (property == null)
            {
                throw new ArgumentException("Argument is not a property", "propertyExpression");
            }

            return property.Name;
        }
        #endregion
    }
}
